package com.wlxt.springcloud.book.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.wlxt.springcloud.book.entity.Book;
import com.wlxt.springcloud.book.entity.Borrow;
import com.wlxt.springcloud.book.pojo.ResultDTO;
import com.wlxt.springcloud.book.service.BookService;

@RestController
public class BookController {
	
	@Autowired
	private BookService bookService;
	
	@GetMapping("/list_book")
	public ResultDTO listBook() {
		ResultDTO result = new ResultDTO();
		try {
			result.setCode("0");
			result.setMessage("success");
			List<Book> bookList = bookService.findAll();
			result.setData(bookList);
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(e.getClass().getSimpleName());
			result.setMessage(e.getMessage());
		}
		return result;
	}
	
	
	@GetMapping("/info")
	public ResultDTO info(String bid) {
		ResultDTO result = new ResultDTO();
		try {
			result.setCode("0");
			result.setMessage("success");
			Book book = bookService.getInfo(bid);
			result.setData(book);
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(e.getClass().getSimpleName());
			result.setMessage(e.getMessage());
		}
		return result;
	}
	
	@GetMapping("/list_borrow")
	public ResultDTO listBorrow() {
		ResultDTO result = new ResultDTO();
		try {
			result.setCode("0");
			result.setMessage("success");
			List<Borrow> list = bookService.findAllBorrow();
			result.setData(list);
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(e.getClass().getSimpleName());
			result.setMessage(e.getMessage());
		}
		return result;
	}
	
	
	@RequestMapping("/borrow")
	public ResultDTO borrow(String mobile, String bid, String takeDate, String returnDate) {
		Date tdate = null;
		Date rdate = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		
		try {
			tdate = sdf.parse(takeDate);
			rdate = sdf.parse(returnDate);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		ResultDTO result = new ResultDTO();
		try {
			bookService.borrow(bid, mobile, tdate, rdate);
			result.setMessage("success");
			result.setCode("0");
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(e.getClass().getSimpleName());
			result.setMessage(e.getMessage());
		}
		return result;
	}
	
	
}
